package https;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;


import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import https.callback.BaseCommonCallback;
import common.Constant;
import https.bean.InterNetControllerBean;
import utils.MyLogUtils;
import utils.SPUtils;
import utils.SignatureUtil;
import utils.ToastUtils;
import view.WaitingDialog;

/**
 * Created by Administrator on 2017/2/27.
 * 获取网络信息
 * param url 要访问的url
 * param handler 返回的handler
 * param dataMap 要传入的参数
 * param flag 判断传入者身份
 * flag2 判断传入者身份2
 * showDialog 是否显示等待遮罩
 */

public class InterNetController {
    private final String TAG = "HttpController";

    public InterNetController(final Context context, final String url, final Handler handler, final HashMap<String, ?> dataMap, final int flag) {
        new InterNetController(context, url, handler, dataMap, flag, 0, true);
    }

    public InterNetController(final Context context, final String url, final Handler handler, final HashMap<String, ?> dataMap, final int flag, boolean showDialog) {
        new InterNetController(context, url, handler, dataMap, flag, 0, showDialog);
    }

    public InterNetController(final Context context, final String url, final Handler handler, final HashMap<String, ?> dataMap, final int flag, final int flag2) {
        new InterNetController(context, url, handler, dataMap, flag, flag2, true);
    }

    public InterNetController(final Context context, final String url, final Handler handler, final HashMap<String, ?> dataMap, final int flag, final int flag2, final boolean showDialog) {
        MyLogUtils.e(TAG, context.getClass().getName() + "-----" + url + "\n");
        String token = SPUtils.getSharedPreferences().getString(Constant.TOKEN, "");
        RequestParams requestParams = new RequestParams(url);
        String random = SignatureUtil.GetRandom(32);
        final String timeStamp = SignatureUtil.GetTimeStamp();
        requestParams.addParameter("rdStr", random);
        requestParams.addParameter("timestamp", timeStamp);
        requestParams.addParameter("token", token);
        final HashMap<String, String> hashMap = new HashMap<>();
        if (dataMap != null) {
            if (dataMap.size() != 0) {
                Set set = dataMap.keySet();
                Iterator iter = set.iterator();//遍历插入
                while (iter.hasNext()) {
                    String key = (String) iter.next();
                    requestParams.addParameter(key, dataMap.get(key));
                    hashMap.put(key, String.valueOf(dataMap.get(key)));
                }
            }
        }
        hashMap.put("rdStr", random);
        hashMap.put("timestamp", timeStamp);
        hashMap.put("token", token);
        String id = SPUtils.getSharedPreferences().getString(Constant.USER_ID, "");
        if (!TextUtils.isEmpty(id)) {
            requestParams.addParameter("ac_id", id);
            hashMap.put("ac_id", id);
        }
        requestParams.addParameter("sign", SignatureUtil.getSignature(hashMap));
        requestParams.setConnectTimeout(5000);

        if (showDialog) {
            WaitingDialog.showWaitingDialog(context);
        }

        x.http().post(requestParams, new BaseCommonCallback(context) {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                MyLogUtils.e(TAG, "onSuccess: " + context.getClass().getName() + "-----" + url + "\n" + result);
                if (!BaseCommonCallback.stop) {
                    Message msg = new Message();
                    msg.what = Constant.ERROR_CODE_SUCCESS;
                    msg.arg1 = flag;
                    msg.arg2 = flag2;
                    msg.obj = result;
                    handler.sendMessage(msg);
                } else {
                    MyLogUtils.e(TAG, "onSuccess: " + "stop");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLogUtils.e(TAG, "onError:-----" + context.getClass().getName() + "-----" + url + "-----" + "\n" + ex.getMessage());
                Message msg = new Message();
                msg.what = Constant.ERROR_CODE_FAILD;
                InterNetControllerBean interNetControllerBean = new InterNetControllerBean();
                interNetControllerBean.setContext(context);
                interNetControllerBean.setUrl(url);
                interNetControllerBean.setFlag(flag);
                interNetControllerBean.setDataMap(dataMap);
                if (!isNetworkAvailable(context)) {
                    //网络不可用时
                    interNetControllerBean.setNetworkError(true);
                } else {
                    interNetControllerBean.setNetworkError(false);
                }
                msg.obj = interNetControllerBean;
                if (handler != null) {
                    handler.sendMessage(msg);
                }
                ToastUtils.shortToast("访问错误" + ex.getMessage());
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
                if (showDialog) {
                    WaitingDialog.closeWaitingDialog();
                }
            }

            @Override
            public void onFinished() {
                if (showDialog) {
                    WaitingDialog.closeWaitingDialog();
                }
                System.gc();
                if (handler != null) {
                Message msg = new Message();
                msg.what = Constant.ERROR_CODE_FINISH;
                msg.arg1 = flag;
                handler.sendMessage(msg);
                }
            }
        });
    }
    /**
     * 检测当的网络（WLAN、3G/2G）状态
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

}
